import datetime
import hashlib
import os
import re
import numpy

# 抛出错误
def throw(err):
    if err is None:
        print("throw函数调用方式错误，缺少err")
        raise Exception('缺少err')
    print(err)
    raise Exception(err)


# 获取形如 20210929170621 的时间字符串
def getCurrentTimeStr() -> str:
    time_stamp = datetime.datetime.now()
    return time_stamp.strftime('%Y%m%d%H%M%S')


# 获取形如 2021-09-29 17:06:21 的时间字符串
def getCurrentTimeFormat() -> str:
    time_stamp = datetime.datetime.now()
    return time_stamp.strftime('%Y-%m-%d %H:%M:%S')


# 获取形如 2021-10-5 的时间字符串
def getCurrentDateStr() -> str:
    time_stamp = datetime.datetime.now()
    return time_stamp.strftime('%Y-%m-%d')


# 获取一个字符串的md5
def getMd5(data) -> str:
    return hashlib.md5(data.encode(encoding='UTF-8')).hexdigest()


# 获取四个方向
def get4direct(x, y):
    up = {
        'x': x,
        'y': y + 1
    }
    down = {
        'x': x,
        'y': y - 1
    }
    left = {
        'x': x - 1,
        'y': y
    }
    right = {
        'x': x + 1,
        'y': y
    }
    return up, down, right, left


# 获取sgf中指定的数据 如RE PB
def get_sgf_info(data, target, default):
    p1 = re.compile(r"{}\[(.*?)]".format(target), re.S)
    res = re.findall(p1, data)
    # 没匹配到 返回的默认值 unknown
    if default == '':
        default = 'unknown'
    if len(res) == 0:
        return default
    else:
        return res[0]


# 获取目录下所有文件
def get_all_file(current: str) -> list:
    return os.listdir(current)


# 获取配置文件的键值
def get_config_by_key(config, key: str):
    if key in config:
        return config[key]
    else:
        return None


# 获取数组的最后一项
def get_list_last_item(data: list):
    return data[len(data) - 1]


def forfor(a):
    return [item for sublist in a for item in sublist]
